package com.ys.controller.api.business;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.entity.base.TbPlatform;
import com.ys.entity.business.TpAmazonShopProduct;
import com.ys.entity.shiro.LoginUser;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsCol;
import com.ys.service.business.TpAmazonShopProductService;
import com.ys.service.log.ApiLogService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.AESUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.ApiResponse;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/tpAmazonShopProduct")
public class ApiInterTpAmazonShopProductController {
    public static Long MENU_ID = 10194L;
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTpAmazonShopProductController.class);

    @Autowired
    private TpAmazonShopProductService tpAmazonShopProductService;


    @Autowired
    private CommonApiService<TpAmazonShopProduct> commonApiService;

    @Autowired
    private ApiLogService apiLogService;



    @RequiresPermissions("tpAmazonShopProduct:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TpAmazonShopProduct cond){
        cond.addLeftJoin("TP_AmazonShop tas on tas.id = A.shopId")//运营店铺信息
                .addField("tas.shopUser AS shopUser,tas.shopName AS shopName")
        .addLeftJoin("TP_AmazonSeller tsell on tsell.id = tas.AmazonSellerId")//卖家计划
        .addLeftJoin("TB_Site ts on ts.id = tas.SiteId")//站点
        .addLeftJoin("TB_Country tc on tc.id = ts.CountryId")//国家
                .addField("tc.name AS countryName")
        .addLeftJoin("THR_OperateCompanyApply THRO on THRO.VGsBm=tsell.Vgsbm")//运营公司
                .addField("THRO.VGsBm AS vgsbm,THRO.VGsJc AS vgsjc,THRO.cuser cuser")
        .addLeftJoin("TP_ProductActive tpa on tpa.code = A.code")//listing
                .addField("tpa.name AS name")
        .addLeftJoin("TP_AmazonRegionItem t3 ON A.marketplaceId = t3.marketplaceId")//地区币种
                .addField("t3.currencyCode AS currencyCode")
        .setOrderby("A.createTime DESC");
        cond = commonApiService.dataAuth(MENU_ID, cond);
        return commonApiService.searchLay(cond);
    }


    /**
     * 修改
     */
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData) {
        try {
            logger.info("SKU保存传参：" + params);
            //修改
            return tpAmazonShopProductService.update(params,subData);
        } catch (Exception e) {
            logger.error("修改SKU保存出错：", e.getMessage(), e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 删除
     */
    @PostMapping("/del")
    @ResponseBody
    public R del(Long id){
        try {
            return tpAmazonShopProductService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败，请联系客服");
        }
    }


    /**
     * 删除
     */
    @PostMapping("/delByIds")
    @ResponseBody
    public R delByIds(@RequestParam Map<String, Object> params){
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            for(String id:idArr){
                tpAmazonShopProductService.delete(Long.parseLong(id));
            }
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败，请联系客服");
        }
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TpAmazonShopProduct cond,String conditions){
        try {
            cond.setPage(0).setSize(999999);
            cond.addLeftJoin("TP_AmazonShop tas on tas.id = A.shopId")//运营店铺信息
                    .addField("tas.shopUser AS shopUser,tas.shopName AS shopName")
                    .addLeftJoin("TP_AmazonSeller tsell on tsell.id = tas.AmazonSellerId")//卖家计划
                    .addLeftJoin("TB_Site ts on ts.id = tas.SiteId")//站点
                    .addLeftJoin("TB_Country tc on tc.id = ts.CountryId")//国家
                    .addField("tc.name AS countryName")
                    .addLeftJoin("THR_OperateCompanyApply THRO on THRO.VGsBm=tsell.Vgsbm")//运营公司
                    .addField("THRO.VGsBm AS vgsbm,THRO.VGsJc AS vgsjc")
                    .addLeftJoin("TP_ProductActive tpa on tpa.code = A.code")//listing
                    .addField("tpa.name AS name")
                    .addLeftJoin("TP_AmazonRegionItem t3 ON A.marketplaceId = t3.marketplaceId")//地区币种
                    .addField("t3.currencyCode AS currencyCode")
                    .setOrderby("A.createTime DESC");
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TP_AmazonShopProduct)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<TpAmazonShopProduct> util = new ExportExcelUtils<>(new TpAmazonShopProduct());
            String toFilePath = util.exportExcel(listData, listField, "Amazon商品管理表");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }


    /**
     * 手动调用
     */
    @PostMapping("/manua")
    @ResponseBody
    public R manua(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            Date nowDate = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String nowDateStr = simpleDateFormat.format(nowDate);
            LoginUser loginUser = ShiroUtils.getLoginUser();
            String loginUserId = loginUser.getUserId();
            TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();
            String updateUserId = String.valueOf(tsUserChange.getId());
            List<Map<String, Object>> amazonShopProductList = new TpAmazonShopProduct()
                    .addLeftJoin("TP_AmazonShop tas on A.ShopId = tas.id")
                        .addField("tas.sellerId as sellerId")
                    .addLeftJoin("TP_AmazonSeller tsell on tsell.id = tas.AmazonSellerId")//卖家管理
                         .addField("tsell.refreshToken as refreshToken,tsell.regionCode as regionCode,tsell.regionName")
                    .addLeftJoin("TB_Site ts on ts.id = tas.SiteId")//站点
                        .addField("ts.AmazonMarketplaceId AS marketplaceId")
                    .addLeftJoin("TB_Country tc on tc.id = ts.CountryId")//国家
                    .addField("tc.name AS countryName,tc.code AS countryCode")
                    .addLeftJoin("TP_AmazonRegion tar on tar.Code = ts.regionCode")//平台地区
                        .addField("tar.AwsRegion awsRegion,tar.AmazonServiceUrl amazonServiceUrl,tar.code amazonRegionCode")
                    .where("A.id IN(" + params.get("list").toString() + ")")
                    .queryMap();
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(amazonShopProductList));

            //平台
            TbPlatform tbPlatform = new TbPlatform().setCode("PTBM001").queryFirst();
            if (tbPlatform == null){
                return R.error("平台PTBM001信息为空");
            }
            String encryptSecret = AESUtil.aesDecrypt(tbPlatform.getEncryptSecret());

            if (amazonShopProductList != null && amazonShopProductList.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    //获取区域对应的端点枚举，取不到直接跳转过
                    if (jsonObject.get("awsRegion") != null) {
                        jsonObject.put("type",0);
                        ApiResponse apiResponse = tpAmazonShopProductService.getAsinAndProductInfo(jsonObject, nowDateStr, updateUserId,encryptSecret);
                        if (apiResponse.getCode() == 500){
                            apiLogService.addApiLog("Amazon","GetAsinAndProductInfoSd","手动获取亚马逊订单信息，条件queryParams：" + JSON.toJSONString(jsonObject), apiResponse.getMessage(),apiResponse.getCode(), apiResponse.getMsg());
                            return R.error(apiResponse.getMessage());
                        }
                    }else {
                        return R.error("平台地区信息未维护齐全!");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("手动获取失败,失败原因:"+e.getMessage());
        }
        return R.ok("重新刷新成功!");
    }

    /**
     * 打印
     */
    @PostMapping("/doPrint")
    @ResponseBody
    public R doPrint(HttpServletRequest request, Long id){
        try {
            return tpAmazonShopProductService.doPrint(id);
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }

    @RequestMapping("/searchFbaPlan")
    @ResponseBody
    public LayuiTableVoJA searchFbaPlan(@ModelAttribute TpAmazonShopProduct cond){
        cond.addField("A.id amazonShopProductId");
        return commonApiService.searchLay(cond);
    }

}
